package alipay

import (
	"github.com/gin-gonic/gin"
	"github.com/gogap/logs"
	"go.uber.org/zap"
	"yundian/internel/app/logic"
	"yundian/internel/pkg/alipay"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

// 登录签名
func HandlerAliPayLoginSing(c *gin.Context) {
	wxConfig := logic.NewSettingLogic().GetAliPaySetting()

	info, sing, err := alipay.AuthLoginSing(wxConfig.AppId)
	if err != nil {
		Response(c)(err.Error(), CodeInternalServerError, nil)(OK)
		return
	}

	Response(c)("", CodeSuccess, map[string]interface{}{
		"info": info,
		"sing": sing,
	})(OK)
}

func HandlerAliPayLogin(c *gin.Context) {
	param := &struct {
		AuthCode string `json:"authCode" form:"authCode"`
	}{}
	err := c.Bind(param)
	if err != nil {
		Response(c)(err.Error(), CodeInvalidParam, nil)(BadRequest)
		return
	}
	//param.AuthCode = "4f1d3a9f8c964fcd95b92cd4ae46YB74"
	//获取支付宝应用信息
	wxConfig := logic.NewSettingLogic().GetAliPaySetting()
	logs.Info("支传宝登录", wxConfig.AppId)
	respData, err := alipay.AuthToken(param.AuthCode, wxConfig.AppId)
	if err != nil {
		zap.L().Error(err.Error())
		Response(c)(err.Error(), CodeError, respData.ErrorResponse)(Error)
		return
	}

	// 处理业务逻辑
	loginResult, err := alipay.Login(respData, wxConfig.AppId)
	if err != nil {
		zap.L().Error(err.Error())
		Response(c)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 响应给前端
	loginResult.Openid = respData.Response.UserId
	logs.Info("123213=============>", respData.Response)
	Response(c)("", CodeSuccess, loginResult)(OK)
}

func HandlerAppAliPayLogin(c *gin.Context) {
	param := &struct {
		Phone    string `json:"phone" form:"phone"`
		Password string `json:"password" form:"password"`
	}{}
	dingo.ErrorIf(c.ShouldBindJSON(param)).Unwrap()

	PASSWORD := "123456"
	PHONE := "17788888888"
	appId := "2021002110678996"
	respData := &alipay.GetAuthTokenResponse{}

	PHONE1 := PHONE
	PHONE2 := "17766666666"
	PHONE3 := "17799999999"
	if param.Phone == PHONE1 {
		respData = &alipay.GetAuthTokenResponse{
			Response: alipay.AuthTokenResponse{UserId: "2088002761459372"},
		}
	} else if param.Phone == PHONE2 {
		PHONE = PHONE2
		respData = &alipay.GetAuthTokenResponse{
			Response: alipay.AuthTokenResponse{UserId: "2088912007079290"},
		}
	} else if param.Phone == PHONE3 {
		PHONE = PHONE3
		respData = &alipay.GetAuthTokenResponse{
			Response: alipay.AuthTokenResponse{UserId: "2088932450165911"},
		}
	} else {
		Response(c)("登录失败，请检查帐号/密码是否正确", CodeInvalidParam, nil)(Error)
		return
	}

	if param.Phone != PHONE || param.Password != PASSWORD {
		Response(c)("登录失败，请检查帐号/密码是否正确", CodeInvalidParam, nil)(Error)
		return
	}

	loginResult, err := alipay.AccountsLogin(respData, appId)
	if err != nil {
		zap.L().Error(err.Error())
		Response(c)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 响应给前端
	Response(c)("", CodeSuccess, loginResult)(OK)
}
